package com.terry.bobobo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import weibo4j.Paging;
import weibo4j.Status;
import weibo4j.Weibo;
import weibo4j.WeiboException;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.TabHost.OnTabChangeListener;

/**
 * @author Terry E-mail: yaoxinghuo at 126 dot com
 * @version create: 2010-10-25 下午01:07:02
 */
public class TimelineActivity extends TabActivity implements
		OnTabChangeListener, OnScrollListener {
	private TabHost timelineTabHost;

	private SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");

	private Weibo weibo = null;

	private ListView timeline_my = null;
	private ListView timeline_friends = null;
	private ListView timeline_public = null;
	private ArrayList<HashMap<String, Object>> timelineItem_my = new ArrayList<HashMap<String, Object>>();
	private ArrayList<HashMap<String, Object>> timelineItem_friends = new ArrayList<HashMap<String, Object>>();
	private ArrayList<HashMap<String, Object>> timelineItem_public = new ArrayList<HashMap<String, Object>>();
	private SimpleAdapter timelineAdapter_my = null;
	private SimpleAdapter timelineAdapter_friends = null;
	private SimpleAdapter timelineAdapter_public = null;
	private int paging_my = 1;
	private int paging_friends = 1;
	private int paging_public = 1;

	private ProgressDialog progress;

	private boolean actionUpdate = false;// false是全部刷新 true为原基础上增加
	private boolean readyToAppend = false;

	private static final int UPDATE_FRIENDS_TIMELINE = 0;
	private static final int UPDATE_PUBLIC_TIMELINE = 1;
	private static final int UPDATE_MY_TIMELINE = 2;

	private static final int UPDATE_HIDE_PROGRESS = 3;
	// private static final int UPDATE_SHOW_PROGRESS = 4;

	private static final int MENU_REFRESH = 1;

	private int currentTab = UPDATE_FRIENDS_TIMELINE;

	private UIHandler updateUIHandler = new UIHandler();
	private WeiboHandler weiboHandler = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		HandlerThread handlerThread = new HandlerThread(
				"sinaweibo_timelineActivity");
		handlerThread.start();
		weiboHandler = new WeiboHandler(handlerThread.getLooper());

		timelineTabHost = this.getTabHost();// 从TabActivity上面获取放置Tab的TabHost
		LayoutInflater.from(this).inflate(R.layout.timeline,
				timelineTabHost.getTabContentView(), true);
		// from(this)从这个TabActivity获取LayoutInflater
		// R.layout.main 存放Tab布局
		// 通过TabHost获得存放Tab标签页内容的FrameLayout
		// 是否将inflate 拴系到根布局元素上

		timelineTabHost.addTab(timelineTabHost.newTabSpec(
				String.valueOf(UPDATE_FRIENDS_TIMELINE))
				.setIndicator("Friends Timeline",
						getResources().getDrawable(R.drawable.icon))
				.setContent(R.id.timeline_friends));
		timelineTabHost.addTab(timelineTabHost.newTabSpec(
				String.valueOf(UPDATE_PUBLIC_TIMELINE)).setIndicator(
				"Public Timeline", getResources().getDrawable(R.drawable.icon))
				.setContent(R.id.timeline_public));
		timelineTabHost.addTab(timelineTabHost.newTabSpec(
				String.valueOf(UPDATE_MY_TIMELINE)).setIndicator("My Timeline",
				getResources().getDrawable(R.drawable.icon)).setContent(
				R.id.timeline_my));
		timelineTabHost.setOnTabChangedListener(this);

		timeline_my = (ListView) findViewById(R.id.timeline_list_my);
		timeline_friends = (ListView) findViewById(R.id.timeline_list_friends);
		timeline_public = (ListView) findViewById(R.id.timeline_list_public);

		timeline_friends.setOnScrollListener(this);
		timeline_public.setOnScrollListener(this);
		timeline_my.setOnScrollListener(this);

		timelineAdapter_my = new SimpleAdapter(TimelineActivity.this,
				timelineItem_my, R.layout.timeline_list, new String[] {
						"t_name", "t_content", "t_time" }, new int[] {
						R.id.t_name, R.id.t_content, R.id.t_time });
		timelineAdapter_friends = new SimpleAdapter(TimelineActivity.this,
				timelineItem_friends, R.layout.timeline_list, new String[] {
						"t_name", "t_content", "t_time" }, new int[] {
						R.id.t_name, R.id.t_content, R.id.t_time });
		timelineAdapter_public = new SimpleAdapter(TimelineActivity.this,
				timelineItem_public, R.layout.timeline_list, new String[] {
						"t_name", "t_content", "t_time" }, new int[] {
						R.id.t_name, R.id.t_content, R.id.t_time });
		timeline_my.setAdapter(timelineAdapter_my);
		timeline_friends.setAdapter(timelineAdapter_friends);
		timeline_public.setAdapter(timelineAdapter_public);

		SharedPreferences user = getSharedPreferences(MainActivity.PREFS_NAME,
				0);
		String token = user.getString("token", "");
		String secret = user.getString("secret", "");
		weibo = new Weibo();
		weibo.setToken(token, secret);

		onTabChanged(String.valueOf(UPDATE_FRIENDS_TIMELINE));

	}

	private void showProgressDialog() {
		progress = ProgressDialog.show(this, "", "Loading, please wait...",
				true, true);
	}

	class UIHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UPDATE_FRIENDS_TIMELINE:
				timelineAdapter_friends.notifyDataSetChanged();
			case UPDATE_PUBLIC_TIMELINE:
				timelineAdapter_public.notifyDataSetChanged();
				break;
			case UPDATE_MY_TIMELINE:
				timelineAdapter_my.notifyDataSetChanged();
				break;
			case UPDATE_HIDE_PROGRESS:
				break;
			}
			if (progress != null) {
				progress.dismiss();
				progress = null;
			}
			readyToAppend = true;
		}
	}

	class WeiboHandler extends Handler {
		public WeiboHandler() {

		}

		public WeiboHandler(Looper looper) {
			super(looper);
		}

		private void handleException(WeiboException e) {
			String m = null;
			int statusCode = e.getStatusCode();
			switch (statusCode) {
			case -1:
				m = "Please check your network";
				break;
			case 400:
				m = "Please check your input";
				break;
			case 401:
				m = "You token invalid, please oauth";
				break;
			default:
				m = "Sorry, error occured, try again later";

			}
			Toast.makeText(TimelineActivity.this, m, Toast.LENGTH_LONG).show();
		}

		@Override
		public void handleMessage(Message msg) {
			if (!isNetworkAvailable()) {
				updateUIHandler.sendEmptyMessage(UPDATE_HIDE_PROGRESS);
				Toast.makeText(TimelineActivity.this,
						"Please check your network", Toast.LENGTH_LONG).show();
				return;
			}
			readyToAppend = false;
			List<Status> statuses = null;
			int tab = msg.what;
			switch (tab) {
			case UPDATE_FRIENDS_TIMELINE:
				try {
					statuses = weibo.getFriendsTimeline(new Paging(
							paging_friends));
					paging_friends++;
					if (!actionUpdate)
						timelineItem_friends.clear();
				} catch (WeiboException e) {
					handleException(e);
				}
				break;
			case UPDATE_PUBLIC_TIMELINE:
				try {
					statuses = weibo
							.getPublicTimeline(new Paging(paging_public));
					paging_public++;
					if (!actionUpdate)
						timelineItem_public.clear();
				} catch (WeiboException e) {
					handleException(e);
				}
				break;
			case UPDATE_MY_TIMELINE:
				try {
					statuses = weibo.getUserTimeline(new Paging(paging_my));
					paging_my++;
					if (!actionUpdate)
						timelineItem_my.clear();
				} catch (WeiboException e) {
					handleException(e);
				}
				break;
			}
			if (statuses != null && statuses.size() > 0) {
				for (Status s : statuses) {
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("t_name", s.getUser().getName());
					map.put("t_content", s.getText());
					map.put("t_time", sdf2.format(s.getCreatedAt()));
					switch (tab) {
					case UPDATE_FRIENDS_TIMELINE:
						timelineItem_friends.add(map);
						break;
					case UPDATE_PUBLIC_TIMELINE:
						timelineItem_public.add(map);
						break;
					case UPDATE_MY_TIMELINE:
						timelineItem_my.add(map);
						break;
					}

				}
				updateUIHandler.sendEmptyMessage(msg.what);
			} else
				updateUIHandler.sendEmptyMessage(UPDATE_HIDE_PROGRESS);
		}
	}

	@Override
	public void onTabChanged(String tagId) {
		int action = UPDATE_FRIENDS_TIMELINE;
		if (tagId.equals(String.valueOf(UPDATE_PUBLIC_TIMELINE)))
			action = UPDATE_PUBLIC_TIMELINE;
		else if (tagId.equals(String.valueOf(UPDATE_MY_TIMELINE)))
			action = UPDATE_MY_TIMELINE;
		currentTab = action;
		switch (action) {
		case UPDATE_FRIENDS_TIMELINE:
			if (timelineItem_friends.size() > 0)
				return;
			break;
		case UPDATE_PUBLIC_TIMELINE:
			if (timelineItem_public.size() > 0)
				return;
			break;
		case UPDATE_MY_TIMELINE:
			if (timelineItem_my.size() > 0)
				return;
			break;
		}
		weiboHandler.sendEmptyMessage(action);
		showProgressDialog();
	}

	public boolean isNetworkAvailable() {
		Context context = getApplicationContext();
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			return false;
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuItem refreshMenu = menu.add(0, MENU_REFRESH, 0, "Refresh");
		refreshMenu.setIcon(android.R.drawable.ic_menu_rotate);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_REFRESH:
			actionUpdate = false;
			weiboHandler.sendEmptyMessage(currentTab);
			switch (currentTab) {
			case UPDATE_FRIENDS_TIMELINE:
				paging_friends = 1;
				break;
			case UPDATE_PUBLIC_TIMELINE:
				paging_public = 1;
				break;
			case UPDATE_MY_TIMELINE:
				paging_my = 1;
				break;
			}
			showProgressDialog();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		if (readyToAppend && totalItemCount > 17
				&& (firstVisibleItem + visibleItemCount) > (totalItemCount - 2)) {
			actionUpdate = true;
			showProgressDialog();
			weiboHandler.sendEmptyMessage(currentTab);
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
	}
}
